package com.example.tangyee.fragment;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tangyee.activity.BloodGlucoseActivity;
import com.example.tangyee.activity.DoctorsActivity;
import com.example.tangyee.activity.ExerciseActivity;
import com.example.tangyee.activity.HealthVideoPlayerActivity;
import com.example.tangyee.activity.HealthVideosActivity;
import com.example.tangyee.activity.KnowledgeDetailActicity;
import com.example.tangyee.MainActivity;
import com.example.tangyee.R;
import com.example.tangyee.activity.PredictActivity;
import com.example.tangyee.activity.RecipeDetailActivity;
import com.example.tangyee.activity.RecipesActivity;
import com.example.tangyee.bean.Article;
import com.example.tangyee.bean.HealthVideo;
import com.example.tangyee.bean.Recipe;
import com.example.tangyee.utils.GetArticles;
import com.example.tangyee.utils.GetHealthVideos;
import com.example.tangyee.utils.GetRecipes;
import com.example.tangyee.utils.GlideApp;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class HomeFragment extends Fragment {

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    private Unbinder mUnbinder;

    @BindView(R.id.home_article_1)
    View article1;
    @BindView(R.id.home_article_2)
    View article2;
    @BindView(R.id.home_article_3)
    View article3;

    @BindView(R.id.banner)
    Banner mBanner;

    @BindView(R.id.blood_glucose)
    View bloodGlucose;
    @BindView(R.id.doctor)
    View doctor;
    @BindView(R.id.exercise)
    View exercise;
    @BindView(R.id.prediction)
    View predict;

    @BindView(R.id.title_knowledge)
    View titleKnowledge;
    @BindView(R.id.title_video)
    View titleVideo;
    @BindView(R.id.title_diet)
    View titleDiet;

    @BindView(R.id.home_video_image1)
    ImageView homeVideoImage1;
    @BindView(R.id.home_video_image2)
    ImageView homeVideoImage2;
    @BindView(R.id.home_video_image3)
    ImageView homeVideoImage3;

    @BindView(R.id.recipe1)
    View recipe1;
    @BindView(R.id.recipe2)
    View recipe2;
    @BindView(R.id.recipe3)
    View recipe3;
    @BindView(R.id.recipe4)
    View recipe4;
    @BindView(R.id.recipe5)
    View recipe5;

    private GetArticles mGetArticles;
    private GetRecipes mGetRecipes;
    private GetHealthVideos mGetHealthVideos;
    private int flag = 0;

    RefreshLayout refreshLayout;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content_home, container, false);
        mUnbinder = ButterKnife.bind(this,view);

        /*
        * 下拉刷新
        * */
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new MaterialHeader(getActivity()));
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            if (mGetArticles != null)
                mGetArticles.cancel(true);
            if (mGetHealthVideos != null)
                mGetHealthVideos.cancel(true);
            if (mGetRecipes != null)
                mGetRecipes.cancel(true);
            flag = 0;
            mGetRecipes = new GetRecipes(1, 5, recipeExecute);
            mGetRecipes.execute();
            mGetHealthVideos = new GetHealthVideos( 1, 10, videoExecute);
            mGetHealthVideos.execute();
            mGetArticles = new GetArticles(1, 3, articleExecute);
            mGetArticles.execute();
        });

        onSaveInstanceState(savedInstanceState);
        // 设置Banner
        initBanner();

        // 获取文章
        getArticles();

        // 设置标题
        setTitles();

        // 获取视频图片
        getVideoImages();

        // 获取菜谱
        getRecipes();

        bloodGlucose.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), BloodGlucoseActivity.class);
            startActivity(intent);
        });
        doctor.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), DoctorsActivity.class);
            startActivity(intent);
        });
        exercise.setOnClickListener(v -> {
            startActivity(ExerciseActivity.getExerciseActivityIntent(getActivity()));
        });
        predict.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), PredictActivity.class);
            startActivity(intent);
        });

        return view;
    }

    private void updateRefreshFlag() {
        flag ++;
        Log.d("HomeFragment", "updateRefreshFlag: " + flag);
        if (flag >= 3) {
            if (refreshLayout != null)
                refreshLayout.finishRefresh(true);
        } else if (flag < 0) {
            if (refreshLayout != null)
                refreshLayout.finishRefresh(false);
        }
    }

    GetRecipes.OnPostExecute recipeExecute;
    private void getRecipes() {
        View[] recipeViews = new View[]{recipe1, recipe2, recipe3, recipe4, recipe5};
        recipeExecute = items -> {
            if (items == null) {
                flag = -10;
                updateRefreshFlag();
                return;
            }
            updateRefreshFlag();
            for (int i = 0; i < recipeViews.length && i < items.size(); i ++) {
                View view = recipeViews[i];
                Recipe recipe = items.get(i);

                ImageView imageView = view.findViewById(R.id.recipe_image);
                TextView textView = view.findViewById(R.id.title);

                textView.setText(recipe.getRecipeName());

                view.setOnClickListener(v -> {
                    Intent intent = RecipeDetailActivity.getRecipeDetailActivityIntent(getActivity(), recipe);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        imageView.setTransitionName("recipe");
                        startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(getActivity(), imageView, "recipe").toBundle());
                    } else {
                        startActivity(intent);
                    }
                });

                GlideApp.with(getActivity())
                        .load(recipe.getImageUrl())
                        .placeholder(R.drawable.loading)
                        .error(R.drawable.error)
                        .fitCenter()
                        .into(imageView);
            }
        };
        mGetRecipes = new GetRecipes(1, 5, recipeExecute);
        mGetRecipes.execute();
    }

    GetHealthVideos.OnPostExecute videoExecute;
    private void getVideoImages() {
        ImageView[] imageViews = new ImageView[]{homeVideoImage1, homeVideoImage2, homeVideoImage3};
        videoExecute = items -> {
            if (items == null) {
                flag = -10;
                updateRefreshFlag();
                return;
            }
            updateRefreshFlag();
            for (int i = 0; i < imageViews.length && i < items.size(); i ++) {
                ImageView imageView = imageViews[i];
                HealthVideo video = items.get(i);

                imageView.setOnClickListener(v -> HealthVideoPlayerActivity.gotoHealthVideoPlayerActivity(getActivity(), video));

                GlideApp.with(getActivity())
                        .load(video.getImageUrl())
                        .placeholder(R.drawable.loading)
                        .error(R.drawable.error)
                        .fitCenter()
                        .into(imageView);
            }
        };

        mGetHealthVideos = new GetHealthVideos( 1, 10, videoExecute);
        mGetHealthVideos.execute();
    }

    private void setTitles() {
        TextView title1 = titleKnowledge.findViewById(R.id.title);
        TextView more1 = titleKnowledge.findViewById(R.id.more);
        more1.setOnClickListener(v -> ((MainActivity) getActivity()).showFragment(1));
        TextView title2 = titleVideo.findViewById(R.id.title);
        title2.setText("健康视频");
        TextView more2 = titleVideo.findViewById(R.id.more);
        more2.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), HealthVideosActivity.class);
            startActivity(intent);
        });
        TextView title3 = titleDiet.findViewById(R.id.title);
        title3.setText("精选菜谱");
        TextView more3 = titleDiet.findViewById(R.id.more);
        more3.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), RecipesActivity.class);
            startActivity(intent);
        });
    }

    GetArticles.OnPostExecute articleExecute;
    private void getArticles() {
        articleExecute = articles -> {
            if (articles == null) {
                flag = -10;
                updateRefreshFlag();
                return;
            }
            updateRefreshFlag();
            View[] mViews = new View[]{article1, article2, article3};
            for (int i = 0; i < mViews.length && i < articles.size(); i ++) {
                View articleView = mViews[i];
                final Article article = articles.get(i);
                articleView.setOnClickListener(v -> {
                    Intent intent = new Intent(getActivity(), KnowledgeDetailActicity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("knowID", article.getKnowID());
                    bundle.putString("title", article.getTitle());
                    intent.putExtras(bundle);
                    getActivity().startActivity(intent);
                });
                TextView title = articleView.findViewById(R.id.title);
                title.setText(article.getTitle());
                TextView releaseDate = articleView.findViewById(R.id.release_date);
                releaseDate.setText( article.getAuthor() + "    " + article.getReleaseDate() + "    " + article.getCount() + "访问");
                TextView summary = articleView.findViewById(R.id.summary);
                summary.setText(article.getSummary());

                ImageView image = articleView.findViewById(R.id.image);
                GlideApp.with(getActivity())
                        .load(article.getImageUrl())
                        .placeholder(R.drawable.loading)
                        .error(R.drawable.error)
                        .fitCenter()
                        .into(image);
            }
        };
        // 获取文章
        mGetArticles = new GetArticles(1, 3, articleExecute);
        mGetArticles.execute();
    }

    private void initBanner() {
        // 创建图片集合
        List<String> images = new ArrayList<>();
        images.add("https://www.tangyee.com/Content/Images/Carousels/2.jpeg");
        images.add("https://www.tangyee.com/Content/Images/Carousels/3.jpeg");
        images.add("https://www.tangyee.com/Content/Images/Carousels/5.jpeg");
        // 设置轮播图
        mBanner.setImages(images) // 设置图集
                .setDelayTime(3000) // 轮播间隔时间
                .setImageLoader(new GlideImageLoader()) // 设置图片加载器
                // .setBannerStyle(BannerConfig.NUM_INDICATOR)
                .start();
    }

    // 图片加载器
    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            GlideApp.with(context).load(path).into(imageView);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mGetArticles != null) {
            mGetArticles.cancel(true);
        }
        if (mGetHealthVideos != null) {
            mGetHealthVideos.cancel(true);
        }
        if (mGetRecipes != null) {
            mGetRecipes.cancel(true);
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }
}
